package com.furnitur.modules.admin.service.statistics.impl;

import com.furnitur.common.exception.BusinessException;
import com.furnitur.common.utils.SecurityUtils;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.mapper.order.OrderMapper;
import com.furnitur.core.mapper.product.FurnitureMapper;
import com.furnitur.modules.admin.dto.statistics.DashboardStatisticsDTO;
import com.furnitur.modules.admin.dto.statistics.OrderStatisticsDTO;
import com.furnitur.modules.admin.service.merchant.MerchantService;
import com.furnitur.modules.admin.service.statistics.DashboardService;
import com.furnitur.modules.admin.vo.statistics.DashboardStatisticsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private MerchantService merchantService;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private FurnitureMapper furnitureMapper;

    @Override
    public DashboardStatisticsVO getStatistics(DashboardStatisticsDTO dashboardDTO) {
        DashboardStatisticsVO vo = new DashboardStatisticsVO();
        
        // 获取当前商家ID
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            log.error("Current user is null");
            throw new BusinessException("用户未登录");
        }
        log.info("Current user: {}", currentUser);
        
        Long merchantId = currentUser.getId();
        log.info("Using merchant ID: {}", merchantId);
        
        try {
            // 设置今日概览数据
            vo.setTodaySales(orderMapper.getTodaySales(merchantId));
            vo.setTodayOrders(orderMapper.getTodayOrders(merchantId));
            vo.setSalesGrowth(calculateSalesGrowth(merchantId));
            vo.setOrdersGrowth(calculateOrdersGrowth(merchantId));
            
            // 设置商品统计
            vo.setTotalProducts(furnitureMapper.countByMerchantId(merchantId));
            vo.setLowStockProducts(furnitureMapper.countLowStock(merchantId));
            
            // 设置订单统计
            vo.setPendingOrders(orderMapper.countPendingOrders(merchantId));
            vo.setRefundOrders(orderMapper.countRefundOrders(merchantId));
            
            // 设置销售趋势
            OrderStatisticsDTO orderDTO = new OrderStatisticsDTO();
            orderDTO.setMerchantId(merchantId);
            orderDTO.setTimeUnit(dashboardDTO.getTimeUnit());
            orderDTO.setStartDate(dashboardDTO.getStartDate());
            orderDTO.setEndDate(dashboardDTO.getEndDate());

            List<Map<String, Object>> trends = orderMapper.getOrderTrends(orderDTO);
            setTrendData(vo, trends);
            
            // 设置分类统计
            setCategoryStats(vo, merchantId);
            
            // 获取订单完成率
            Double completionRate = orderMapper.calculateCompletionRate(merchantId);
            vo.setCompletionRate(completionRate);
            
            // 获取平均客单价
            BigDecimal averageOrderValue = orderMapper.calculateAverageOrderValue(merchantId);
            vo.setAverageOrderValue(averageOrderValue);
            
            log.info("Dashboard statistics generated successfully for merchant: {}", merchantId);
            
        } catch (Exception e) {
            log.error("Error generating dashboard statistics for merchant: {}", merchantId, e);
            throw new BusinessException("获取统计数据失败");
        }
        
        return vo;
    }
    
    private Double calculateSalesGrowth(Long merchantId) {
        Double todaySales = orderMapper.getTodaySales(merchantId);
        Double yesterdaySales = orderMapper.getYesterdaySales(merchantId);
        if (yesterdaySales == 0) {
            return 0.0;
        }
        return ((todaySales - yesterdaySales) / yesterdaySales) * 100;
    }

    private Double calculateOrdersGrowth(Long merchantId) {
        Integer todayOrders = orderMapper.getTodayOrders(merchantId);
        Integer yesterdayOrders = orderMapper.getYesterdayOrders(merchantId);
        if (yesterdayOrders == 0) {
            return 0.0;
        }
        return ((todayOrders - yesterdayOrders) / (double)yesterdayOrders) * 100;
    }

    private void setTrendData(DashboardStatisticsVO vo, List<Map<String, Object>> trends) {
        if (trends == null || trends.isEmpty()) {
            // 如果没有数据，设置空列表
            vo.setDates(new ArrayList<>());
            vo.setSalesData(new ArrayList<>());
            return;
        }

        List<String> dates = new ArrayList<>();
        List<Double> salesData = new ArrayList<>();

        for (Map<String, Object> trend : trends) {
            if (trend.get("date") != null) {
                dates.add(trend.get("date").toString());
                // 使用 sales 字段而不是 salesAmount
                Object salesObj = trend.get("sales");
                if (salesObj != null) {
                    salesData.add(((Number) salesObj).doubleValue());
                } else {
                    salesData.add(0.0);
                }
            }
        }

        vo.setDates(dates);
        vo.setSalesData(salesData);
        
        log.debug("Trend data processed - dates: {}, sales: {}", dates, salesData);
    }

    private void setCategoryStats(DashboardStatisticsVO vo, Long merchantId) {
        List<Map<String, Object>> stats = orderMapper.getCategoryStats(merchantId);
        List<DashboardStatisticsVO.CategoryStat> categoryStats = new ArrayList<>();
        
        for (Map<String, Object> stat : stats) {
            DashboardStatisticsVO.CategoryStat categoryStat = new DashboardStatisticsVO.CategoryStat();
            categoryStat.setCategoryId(((Number) stat.get("category_id")).longValue());
            categoryStat.setCategoryName((String) stat.get("category_name"));
            categoryStat.setSalesAmount(((Number) stat.get("sales_amount")).doubleValue());
            categoryStat.setOrderCount(((Number) stat.get("order_count")).intValue());
            categoryStats.add(categoryStat);
        }
        
        vo.setCategoryStats(categoryStats);
    }
} 